<script setup lang="ts">
defineOptions({
  name: "alarmTable"
});

import { ref, reactive, toRefs, onMounted, markRaw, nextTick, computed, getCurrentInstance } from "vue";
import { PxMessage } from "px-ui";
import spcCharts from "@/views/machine/components/spcCharts/index.vue";
import * as echarts from "echarts";
import {
  queryWeatherData,
  getFabZone,
  getReadersInZone,
  getPointsCurve,
  addRemake,
  remakeHistory,
  queryChildByTypeCodeAndItemValue,
  getReadersInZoneByType
} from "@/api/machineClass";
import { spcquerySpcAnalysis } from "@/api/spc";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { useRouter } from "vue-router";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import { querySpecValues, getDetectedValuesInPair, queryScadaIndicator, getReadersInZoneByTypes } from "@/api/machineApi";

const router = useRouter();

interface Props {
  /**  有 tab 时传入 */
  activeName?: string;
  /**  当前区域 */
  area?: string;
  /**选中的指标 */
  allCheckoutbox?: any;
  /**选中的区域 */
  checkAreaList?: any;
}

const props = withDefaults(defineProps<Props>(), {});

const { proxy }: any = getCurrentInstance();

const isShowBarChartsRef = ref(false);

const state = reactive<any>({
  queryParams: {
    pageNum: 1,
    pageSize: 10
    // lifecycle: 4
  },
  queryParams2: {
    pageNum: 1,
    pageSize: 10
  },
  queryHistoryParams: {},
  dateRange: [],
  spcOptions: {},
  tableData: [],
  contentList: [],
  pointsList: [],
  areaData: []
});

const { queryParams, spcOptions, queryHistoryParams, dateRange, areaData, tableData, queryParams2, contentList, pointsList } = toRefs(state);

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const loading = ref(false);

const midKey = ref(Date.now());

const filterList = ref([
  {
    value: "LL",
    label: "低"
  },
  {
    value: "MM",
    label: "中"
  },
  {
    value: "HH",
    label: "高"
  }
]);
const typeList = ref([
  {
    value: "hour",
    label: "小时"
  }
]);
const testCompanyList = ref([
  {
    value: 4,
    label: "近4小时"
  },
  {
    value: 8,
    label: "近8小时"
  },
  {
    value: 16,
    label: "近16小时"
  }
]);

const minitesList = ref([
  {
    value: 10,
    label: "10分钟"
  },
  {
    value: 20,
    label: "20分钟"
  },
  {
    value: 30,
    label: "30分钟"
  }
]);

const barChartsRef = ref(null);
let chartsInstance = null;

const activeIndex = ref(0);
const total2 = ref(0);
const searchId = ref("");
const contentVisible = ref(false);
const contentTextVisible = ref(false);
const showBarCharts = ref(false);
const chosedAlarm = ref("");
const dateRangeSpc = ref([]);
const viewAlarm = ref("");
const alarmRemake = ref("");
const hishoryLoading = ref(false);

const handleAreaChange = (val: any) => {
  // queryParams.value[`${val.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] = val;
};

const handleChange = (val: number) => {
  if (val) {
    dateRangeSpc.value = initDate(val);
    console.log(dateRangeSpc.value);
  }
};

// 查询报警明细
const queryTable = async () => {
  loading.value = true;
  // 清空下发图表
  // spcOptions.value = {};
  // if (chartsInstance) {
  //   chartsInstance.clear();
  //   showBarCharts.value = false;
  // }
  await getHotPointes().catch(error => {
    loading.value = false;
  });
  const arr = queryParams.value.point ? [queryParams.value.point] : pointsList.value;
  if (arr.length) {
    getPointNewValue(arr);
  }
};

// 重置筛选条件
const resetTable = async () => {
  queryParams.value.point = "";
  queryParams.value.lifecycle = null;
  dateRangeSpc.value = initDate(4);
  queryTable();
};

// 行点击
const handleClick = row => {
  initSpc(row.hour.split(" ")[0]);
};

const getParams = computed(() => {
  const obj = {
    zones: [],
    types: [],
    factory: {
      id: 1,
      parentCode: "",
      code: "",
      name: "",
      type: "",
      path: "",
      // facCode: "FAC_83abf9",
      principalId: 1,
      principalName: "",
      className: "MACHINE",
      children: [
        {
          id: 1,
          parentCode: "",
          code: "",
          name: "",
          type: "",
          path: "",
          // facCode: "",
          principalId: 1,
          principalName: "",
          className: ""
        }
      ]
    },
    requestId: ""
  };
  obj.types = [...props.allCheckoutbox];
  obj.zones = [...props.checkAreaList];
  return obj;
});

// 循环获取点位列表
const getPointsList = async (param: any, arr) => {
  const pointObj: any = await getReadersInZoneByTypes(param).catch(error => {
    pointsList.value = [];
  });
  if (Object.keys(pointObj) && Object.keys(pointObj).length > 0) {
    Object.keys(pointObj).forEach(el => {
      arr.push(pointObj[el].split("=")[0]);
    });
  } else {
    arr = [];
  }
  pointsList.value = arr;
};

// 根据点位查询点位最新值
const getPointNewValue = async (arr: any) => {
  const res: any = await queryScadaIndicator({
    contentType: "LIST",
    bucketWidth: 1,
    bucketUnit: "hour",
    point: [...arr],
    indicators: ["AVG", "MAX", "MIN", "FIRST", "LAST"],
    startTime: dateRangeSpc.value[0],
    endTime: dateRangeSpc.value[1],
    pageNum: 1,
    pageSize: 10
  }).catch(error => {
    tableData.value = [];
    loading.value = false;
  });
  // const res: any = await querySpecValues(arr);
  // 根据返回的点位最新值数据反查对应指标
  console.log(res.rows, "点位最新值列表！！！！！");
  tableData.value = res?.rows || [];
  loading.value = false;
};

// 循环调用接口获取点位列表
const getHotPointes = async () => {
  let arr = [];
  const obj = {
    ...getParams.value
  };
  await getPointsList(obj, arr);
  // pointsList.value.forEach(el => {
  //   queryHeatMap(el);
  // });
};

const initSpc = async time => {
  const title = "Q部门 VS online检测";
  const param = {
    // facCode: "FAC_83abf9",
    className: "MACHINE",
    zones: props.checkAreaList, // checkAreaList.value
    detectDate: time,
    types: props.allCheckoutbox,
    requestId: ""
  };
  const res: any = await getDetectedValuesInPair(param);
  // isShowBarChartsRef.value = true;
  let arr = [["product", "Q部门", "online检测", "Ai预测"]];
  res.forEach(item => {
    arr.push([item.sampleSpec, Number(item.sampleValueQ), Number(item.sampleValueR), Number(item.sampleValueRAi)]);
  });
  let legendData = res.map(item => item.sampleSpec);
  const data = { arr, legendData };
  const options: UtilsEChartsOption = {
    color: ["#4786FF", "#14C7C7", "#FCD34D"],
    title: {
      text: title,
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      // data: data.legendData,
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "24px",
      top: "15%",
      right: "24px",
      bottom: "5%",
      containLabel: true
    },
    dataset: {
      source: data.arr
    },
    xAxis: {
      type: "category"
      // data: ["12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: [
      {
        type: "value",
        // name: `单位`,
        alignTicks: true,
        axisLine: {
          lineStyle: {
            width: 2
          }
        }
      }
    ],
    series: [
      {
        type: "bar",
        barWidth: 16,
        itemStyle: {
          color: "#4786FF"
        },
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        }
      },
      {
        type: "bar",
        barWidth: 16,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#14C7C7"
        }
      },
      {
        type: "bar",
        barWidth: 16,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#FCD34D"
        }
      }
    ]
  };
  showBarCharts.value = true;
  if (showBarCharts.value) {
    nextTick(() => {
      if (barChartsRef.value) {
        chartsInstance = markRaw(echarts.init(barChartsRef.value));
        chartsInstance.setOption(options);
        // window.addEventListener("resize", handelResize);
        chartsInstance.resize();
        const arr1 = [...props.checkAreaList];
        const arr2 = [res[0].sampleSpec];
        getOnePoint(arr1, arr2); // 默认展示第一个区域的spc
        chartsInstance.on("click", params => {
          console.log(params, "9999999999999999");
          const zones = [...props.checkAreaList];
          const str = res.filter(item => item.sampleSpec === params.name)[0].sampleSpec || "";
          const types = [str];
          getOnePoint(zones, types);
        });
        window.addEventListener("resize", handelResize);
      }
    });
  }
};

const getOnePoint = async (array1, array2) => {
  const obj = {
    zones: array1,
    types: array2,
    factory: {
      id: 1,
      parentCode: "",
      code: "",
      name: "",
      type: "",
      path: "",
      // facCode: "FAC_83abf9",
      principalId: 1,
      principalName: "",
      className: "MACHINE",
      children: [
        {
          id: 1,
          parentCode: "",
          code: "",
          name: "",
          type: "",
          path: "",
          // facCode: "",
          principalId: 1,
          principalName: "",
          className: ""
        }
      ]
    },
    requestId: ""
  };
  const pointObj: any = await getReadersInZoneByTypes(obj);
  let arr = [];
  if (Object.keys(pointObj) && Object.keys(pointObj).length > 0) {
    Object.keys(pointObj).forEach(el => {
      arr.push(pointObj[el].split("=")[0]);
    });
  }
  if (!arr.length) return;
  const params = {
    pointList: [...arr],
    timePeriod: "hour",
    startTime: dateRangeSpc.value[0], // equipdata.value.sampleTime
    endTime: dateRangeSpc.value[1]
  };
  const res: any = await spcquerySpcAnalysis(params);
  const spcList =
    res.length &&
    res.map((item: any) => {
      item.startTime = dateRangeSpc.value[0];
      item.endTime = dateRangeSpc.value[1];
      item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
      return {
        ...item
      };
    });
  spcOptions.value = spcList[0] || {};
  midKey.value = Date.now();
};

const handelResize = () => {
  if (chartsInstance) {
    chartsInstance.resize();
  }
};

// 日期转化
const initDate = (val: number) => {
  const now = new Date();
  const utcTime = now.toISOString();
  const beijingTime = new Date(utcTime).getTime() + 8 * 60 * 60 * 1000;
  const start = beijingTime - val * 60 * 60 * 1000;
  const startTime = new Date(start).toISOString().slice(0, 19).replace("T", " ");
  const endTime = new Date(beijingTime).toISOString().slice(0, 19).replace("T", " ");
  return [startTime, endTime];
};

const getSpcCharts = async str => {
  const params = {
    jobIdList: ["SPC_MACHINE_EXH_ACID"],
    timePeriod: "hour",
    startTime: dateRangeSpc.value[0],
    endTime: dateRangeSpc.value[1]
  };
  const res: any = await spcquerySpcAnalysis(params);
  spcOptions.value = res.length && res[0];
  midKey.value = Date.now();
};

// 分页相关状态
const total = computed(() => tableData.value.length);

// 计算当前页显示的数据
const paginatedData = computed(() => {
  const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const end = start + queryParams.value.pageSize;
  return tableData.value.slice(start, end);
});

onMounted(async () => {
  dateRangeSpc.value = initDate(4);
  console.log(dateRangeSpc.value, props.allCheckoutbox, props.checkAreaList);
  queryTable();
});
</script>

<template>
  <div class="all-point">
    <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
      <px-form-item label="名称" prop="point" style="width: 220px">
        <!-- <px-select v-model="queryParams.point" clearable filterable placeholder="请选择名称">
          <px-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select> -->
        <px-input v-model="queryParams.point" clearable placeholder="请输入名称" />
      </px-form-item>
      <!-- <px-form-item label="级别" prop="alarmLevel" style="width: 220px">
        <px-select v-model="queryParams.alarmLevel" clearable filterable placeholder="请选择级别">
          <px-option v-for="item in filterList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="区域" prop="areaId" style="width: 220px">
        <px-select v-model="searchId" placeholder="请选择区域" filterable @change="handleAreaChange">
          <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
        </px-select>
      </px-form-item> -->
      <!-- <px-form-item label="房间" prop="areaId" style="width: 220px">
      <px-select v-model="queryParams.roomId" clearable filterable placeholder="请选择房间">
        <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
      </px-select>
    </px-form-item> -->
      <px-form-item label="时间日期" style="width: 460px">
        <px-date-picker
          v-model="dateRangeSpc"
          :clearable="false"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :defaultTime="defaultTime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </px-form-item>
      <px-form-item label="周期" prop="lifecycle" style="width: 220px">
        <px-select v-model="queryParams.lifecycle" clearable filterable placeholder="请选择周期" @change="handleChange">
          <px-option v-for="item in testCompanyList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form-item>
    </px-form>
    <px-table
      v-loading="loading"
      :header-cell-style="{ background: '#e7eefb', color: '#000' }"
      border
      :data="paginatedData"
      show-overflow-tooltip
      @row-click="handleClick"
    >
      <px-table-column label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </px-table-column>
      <!-- <px-table-column width="100" label="厂区" align="center" prop="id" /> -->
      <px-table-column label="时间" align="center" prop="hour" width="160" />
      <!-- <px-table-column label="组" align="center" prop="factoryId" /> -->
      <px-table-column label="名称" align="center" prop="point" />
      <!-- <px-table-column label="报警信息" align="center" prop="alarmContent" width="100" /> -->
      <!-- <px-table-column label="级别" align="center" prop="alarmLevel" /> -->
      <px-table-column label="当前值" align="center" prop="last_value" />
      <!-- <px-table-column label="报警限" align="center" prop="settingValue" /> -->
      <!-- <px-table-column label="状态" align="center" prop="alarmStatus" /> -->
      <!-- <px-table-column label="报警持续时间" align="center" prop="alarmDurationTime" width="180" /> -->
      <!-- <px-table-column label="未确认持续时间" align="center" prop="updateTime" width="160" /> -->
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>
    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" />
    <!-- <div class="btn_box">
      <barTitle title="Q部门 VS online检测" />
      <div class="btn_chart">
        <div class="chart_item">
          <div v-show="showBarCharts" ref="barChartsRef" style="width: 100%; min-width: 600px; height: 480px; border: 1px solid #dcdcdc" />
          <div v-show="!showBarCharts" class="echarts-empty">
            <px-empty :image-size="100" />
          </div>
        </div>
        <div class="chart_item">
          <spcCharts ref="spcChartsDom" :key="midKey" :width="600" :height="480" :optionData="spcOptions" color="#3B82F6" />
        </div>
      </div>
    </div> -->
  </div>
</template>

<style lang="scss" scoped>
.all-point {
  width: 100%;

  .btn_box {
    width: 100%;
    margin-top: 16px;

    .btn_chart {
      display: flex;
      flex-flow: row nowrap;
      gap: 16px;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      min-width: 1300px;
      margin-top: 8px;

      .chart_item {
        width: 50%;
        height: 480px;
        margin-bottom: 20px;
        border-radius: 4px;

        .echarts-empty {
          display: flex;
          justify-content: center;
          width: 100%;
          height: 480px;
          margin: auto;
          border: 1px solid #dcdcdc;
        }
      }
    }
  }
}
</style>
